from kafka import KafkaProducer
import json
import time
from tool import *

import os

image_ext = ['.jpg', '.jpeg', '.webp', '.bmp', '.png']


def json_serializer(data):
    return json.dumps(data).encode("utf-8")


def get_image_list(path):
    """
    获取待检测文件夹的图片路径列表

    Args:
        path: 输入需要检测的样本文件夹路径

    Returns:
            返回待检测文件夹中图片路径信息列表
    """
    image_names = []
    for maindir, subdir, file_name_list in os.walk(path):
        for filename in file_name_list:
            apath = os.path.join(maindir, filename)
            ext = os.path.splitext(apath)[1]
            if ext in image_ext:
                image_names.append(apath)
    return image_names


def get_fake_key():
    return "imageKey" + "_" + randomID(18) + "_" + randomPartID(4) + "_" + randomID(1) + "_" + randomID(
        3) + "_" + randomID(2)


def get_fake_value(img):
    return img


# 实例化生产者
producer = KafkaProducer(bootstrap_servers=['121.4.54.122:9092'], api_version=(0, 10))

if __name__ == "__main__":
    while True:

        img_dir_path = 'D:\Desktop\jiaoda_test2'
        files = get_image_list(img_dir_path)
        files.sort()
        for image_name in files:
            with open(image_name, 'rb') as f:
                img_b = f.read()

            fake_key = get_fake_key()
            print(fake_key)
            fake_key = bytes(fake_key, encoding='utf-8')
            fake_value = get_fake_value(img_b)
            producer.send("Itirs_img", fake_value, fake_key)
            producer.send("Itirs_finish_notice", fake_value, fake_key)
            time.sleep(3)